<script lang="ts" setup>
import {onLoad} from "@dcloudio/uni-app";
import {ref} from "vue";
import type {AddressInfo} from "@/interfaces/user";
import {useAddAddressApi, useEditAddressApi} from "@/services/api";
import {useStore} from "vuex";

const addressForm = ref()
const uToastRef = ref()
const store = useStore()
const address = ref<AddressInfo>({
  address: "",
  name: "",
  phone: "",
  isDefault: 0
})
const rules = ref({
  'address': {
    type: 'string',
    required: true,
    message: '请输入地址',
    trigger: ['blur', 'change']
  },
  'name': {
    type: 'string',
    required: true,
    message: '请输入联系人',
    trigger: ['blur', 'change']
  },
  'phone': {
    validator: (rule: any, value: string, callback: any) => {
      if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    },
    required: true,
    trigger: ['blur', 'change']
  }
})
const submit = () => {
  addressForm.value.validate().then(async () => {
    if (address.value.id) {
      await useEditAddressApi(address.value)
    } else {
      address.value.userId = store.getters["auth/getUserId"]
      await useAddAddressApi(address.value)
    }
    uToastRef.value.show({
      message: '提交成功',
      type: 'success',
      complete: () => {
        uni.$emit('init')
        uni.navigateBack()
      }
    })
  }).catch((err: any) => {
    uToastRef.value.show({
      message: err[0].message,
      type: 'error'
    })
  })
}
onLoad((query) => {
  if (query?.data) {
    address.value = JSON.parse(query.data)
  }
})
</script>

<template>
  <view class="container">
    <u-toast ref="uToastRef"></u-toast>
    <u--form
        ref="addressForm"
        :model="address"
        :rules="rules"
        labelPosition="left"
    >
      <u-form-item
          label="地址"
          label-width="120"
          prop="address"
      >
        <u--input
            v-model="address.address"
        ></u--input>
      </u-form-item>
      <u-form-item
          label="联系人"
          label-width="120"
          prop="name"
      >
        <u--input
            v-model="address.name"
        ></u--input>
      </u-form-item>
      <u-form-item
          label="手机号"
          label-width="120"
          prop="phone"
      >
        <u--input
            v-model="address.phone"
        ></u--input>
      </u-form-item>
      <u-form-item
          label="设置默认地址"
          label-width="120"
          prop="isDefault"
      >
        <u-switch v-model="address.isDefault" :activeValue="1" :inactiveValue="0"></u-switch>
      </u-form-item>
      <view class="submit-btn">
        <u-button text="提交" type="error" @click="submit"></u-button>
      </view>
    </u--form>
  </view>
</template>

<style lang="scss" scoped>
.container {
  padding: 12px;
}
</style>